package com.gfm.story.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gfm.story.dao.ChapterDao;
import com.gfm.story.entity.base.PageBean;
import com.gfm.story.entity.base.ResultBean;
import com.gfm.story.entity.story.Book;
import com.gfm.story.entity.story.Chapter;
import com.gfm.story.entity.user.User;
import com.gfm.story.interceptor.UserContext;
import com.gfm.story.service.story.BookService;
import com.gfm.story.service.story.ChapterService;
import com.gfm.story.util.ParamUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javafx.geometry.Pos;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.util.*;

/**
 * @BelongsProject: story
 * @BelongsPackage: com.gfm.story.controller
 * @Author: Administrator
 * @CreateTime: 2019-06-03 15:02
 * @Description: ${Description}
 */
@Api("小说接口")
@Controller
@RequestMapping(value = "Story")
public class StoryController {

    @Resource
    private BookService bookService;

    @Resource
    private  ChapterDao chapterDao;

    @Resource
    private ChapterService chapterService;

    /**
     * 根据条件查询小说
     * @param request
     * @param pageBean
     * @return
     */
    @RequestMapping(value = "getStoryList")
    @ApiOperation(value = "(查询所有小说)根据条件查询小说", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "start", value = "需要查询的页码", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "rows", value = "每页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "nameOrAuthor", value = "个人网站", dataType = "String", paramType = "query", required = false)
    })
    public String getStoryList(HttpServletRequest request, PageBean pageBean, ModelMap modelMap) throws Exception {
        Map<String, Object> map = ParamUtil.getParameterMap(request);
        String nameOrAuthor = request.getParameter("nameOrAuthor");
        if (nameOrAuthor!=null){
            map.put("nameOrAuthor",nameOrAuthor);
        }
        map.put("start", pageBean.getStart());
        map.put("pageSize", pageBean.getRows());
        modelMap.put("StoryList", bookService.getStoryList(map,pageBean.getPage()));
        return "index";
    }




    //最近入库小说30，可根据小说类别分类查询,带分页
    @RequestMapping("getNewBookList")
    public String getNewBookList(HttpServletRequest request,int index,PageBean pageBean,ModelMap modelMap) throws Exception {
        Map<String, Object> map = ParamUtil.getParameterMap(request);
        map.put("start", pageBean.getStart());
        map.put("pageSize", pageBean.getRows());
        modelMap.put("bookList", bookService.getNewBookList(map,pageBean.getPage()));
        modelMap.put("index",index);
        return "ph";

    }


    //全部小说，查找全部类型的小说
    @RequestMapping("getAllCategoryStoryList")
    public String getAllCategoryStoryList(String isLogin, ModelMap modelMap){
        if (isLogin.equals("true")){//用户有登录记录
            User user = UserContext.getUser();
            modelMap.put("user", user);
        }
        Map<String,Object> r = bookService.getAllCategoryStoryList();
        modelMap.put("AllCategoryStoryList",r);
        return "home";
    }

    /**
     * 根据类型查找小说
     * 1.带分页
     *
     * @param pageBean 分页信息start：第几页，rows：每页条数
     * @return
     */
    @RequestMapping("getStoryByCategory")
    public String getStoryByCategory(HttpServletRequest request, PageBean pageBean, ModelMap modelMap) throws Exception {
        Map<String, Object> map = ParamUtil.getParameterMap(request);
        String name = request.getParameter("name");//小说类型
        if (null != name) {
            map.put("name", name);
        }
        map.put("start", pageBean.getStart());
        map.put("pageSize", pageBean.getRows());
        ResultBean resultBean = bookService.getBookListByCategoryName(map);
        modelMap.put("StoryCategoryInfo",resultBean);
        return "fl";
    }

    /**
     * 查询已完结小说(带分页)
     * @param request status:小说状态 1.已完结 2.连载中
     * @param pageBean
     * @param modelMap
     * @return
     */
    @RequestMapping("getStoryEndPage")
    public String getStoryEndPage(String nameOrAuthor,HttpServletRequest request,PageBean pageBean,ModelMap modelMap) throws Exception {
        Map<String, Object> map = ParamUtil.getParameterMap(request);
        String status = request.getParameter("status");//小说类型
        if (null != status) {
            map.put("status", status);
        }
        if (nameOrAuthor!=null){
            map.put("nameOrAuthor",nameOrAuthor);
        }
        map.put("start", pageBean.getStart());
        map.put("pageSize", pageBean.getRows());
        Map map1 = bookService.getBookListByStatus(map,pageBean.getPage());
        modelMap.put("StoryEndList",map1);
        return "wbxs";
    }


    /**
     * 阅读小说(解析)
     * 两种情况：
     * 1.在小说首页开始阅读(默认从第一章)
     * 2.从指定章节开始阅读(根据章节id)
     * @param chapterId
     * @param bookId
     * @param modelMap
     * @return
     */
    @RequestMapping("loadReadBook")
    public String loadReadBook(Long chapterId,Long bookId,ModelMap modelMap){
        Map<String,Object> map1 = new HashMap<String, Object>();
        //
        if (chapterId==null){
            Chapter chapter = new Chapter();
            chapter.setBookId(bookId);
            EntityWrapper<Chapter> wrapper = new EntityWrapper<Chapter>();
            wrapper.eq("book_id", bookId);
            wrapper.orderBy("update_time");
            List<Chapter> chapters = chapter.selectList(wrapper);
            if (chapters.isEmpty()){//不存在章节
                return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
            }
        }
        modelMap.put("chapterInfo", bookService.getChapterInfo(chapterId,bookId));
        return "read";
    }


    /**
     * 阅读上一章
     * @param chapterId
     * @param bookId
     * @param modelMap
     * @return
     */
    @RequestMapping("forward")
    public String forward(Long chapterId,Long bookId,ModelMap modelMap){
        //1.根据bookid查询所有章节，如果当前chapterid=第一章的id时回到目录--重定向
        if (bookId!=null){
            if (chapterId==null){
                return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
            }
            EntityWrapper<Chapter> wrapper = new EntityWrapper<Chapter>();
            wrapper.eq("book_id", bookId);
            wrapper.orderBy("update_time");
            List<Chapter> chapters = chapterService.selectList(wrapper);
            Chapter chapter = new Chapter();
            if (!chapters.isEmpty()){
                chapter = chapters.get(0);
                if (chapter.getId().equals(chapterId)){//当前章节已经是第一章，重定向到小说首页
                    return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
                }
                modelMap.put("chapterInfo", bookService.forward(chapterId,bookId));
            }
        }
        return "read";
    }

    /**
     * 阅读下一章
     * @param chapterId
     * @param bookId
     * @param modelMap
     * @return
     */
    @RequestMapping("back")
    public String back(Long chapterId,Long bookId,ModelMap modelMap){
        //1.根据bookid查询所有章节，如果当前chapterid=第一章的id时回到目录--重定向
        if (bookId!=null){
            if (chapterId==null){
                return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
            }
            EntityWrapper<Chapter> wrapper = new EntityWrapper<Chapter>();
            wrapper.eq("book_id", bookId);
            wrapper.orderBy("id");
            List<Chapter> chapters = chapterService.selectList(wrapper);
            Chapter chapter = new Chapter();
            if (!chapters.isEmpty()){
                Collections.sort(chapters,new Comparator<Chapter>(){
                    @Override
                    public int compare(Chapter o1, Chapter o2) {
                        Long i = o1.getId() - o2.getId();
                        if (i>0){
                            return 1;
                        }else if(i<0){
                            return -1;
                        }
                        return 0;//相等
                    }
                });
                Collections.reverse(chapters);
                chapter = chapters.get(0);
                if (chapter.getId().equals(chapterId)){//当前章节已经是最后一章，重定向到小说首页
                    return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
                }
                modelMap.put("chapterInfo", bookService.Back(chapterId,bookId));
            }
        }
        return "read";
    }

    @RequestMapping("goReadHome")
    public String goReadHome(Long bookId){
        return "redirect:/Chapter/getChapterByBookId?bookId="+bookId;
    }
}
